﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace ERF
{
    /// <summary>
    /// Provides the functionallity of a state machine.
    /// </summary>
    public class StateMachine : GameComponent
    {
        private Stack<State> previousStates;
        private State currentState;
        private ERFGame game;
        private static StateMachine instance;

        /// <summary>
        /// Gets or sets the game that this StateMachine belongs to.
        /// </summary>
        public ERFGame CurrentGame
        {
            get { return game; }
            set { game = value; }
        }


        /// <summary>
        /// Get the previous state from the stack
        /// Getter works same as stack.Pop(state)and removes and returns the state at top of the stack previousStates
        /// </summary>

        public State PreviousState
        {
            get
            {
                if (previousStates.Count == 0)
                    return null;

                return previousStates.Pop();
            }
        }


        /// <summary>
        /// Gets or sets the current state.
        /// Getter works same as stack.Peek and returns the the state at top of the stack previousStates without pushing it
        /// Setter uses Stack.Push(state)
        /// </summary>

        public State CurrentState
        {
            get { return currentState; }
            set
            {
                
                previousStates.Push(currentState);
                currentState = value;
                if (!currentState.Initialized)
                    currentState.Initialize();
                else
                    currentState.Continue();
            }
        }

        /// <summary>
        /// Creates a new instance of StateMachine.
        /// </summary>
        /// <param name="game">The game that this instance belongs to.</param>
        public StateMachine(ERFGame game)
            : base(game)
        {
            previousStates = new Stack<State>(1);
            this.game = game;

        }

        public override void Update(GameTime gameTime)
        {
            currentState.Update(gameTime);
            base.Update(gameTime);
        }

    }
}
